# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import keras
import smtplib
import numpy as np
from email.mime.text import MIMEText
from email.utils import formataddr
from keras.models import Sequential 
from keras.layers import Dense,Dropout
from itemadapter import ItemAdapter
import datetime
from scrapy.utils.project import get_project_settings

class StockPipeline:
    settings = get_project_settings
    model = Sequential()
    ball_item = []
    predict_ball = []

    def train_model(self):
        self.model.add(Dense(10, input_dim=1, activation = 'sigmoid'))
        self.model.add(Dropout(0.5))
        self.model.add(Dense(6, activation = 'sigmoid'))
        self.model.add(Dropout(0.5))
        self.model.add(Dense(2, activation = 'sigmoid'))
        self.model.add(Dropout(0.5))
        self.model.add(Dense(1))
        self.model.compile(loss = 'mse', optimizer = 'sgd')

    def train_data(self,epoch):
        np_ball = np.array(list(map(lambda x:list(map(int,x)),self.ball_item['number'])))
        for i in range(0,np_ball.shape[1]):
            rdnum = np.random.randint(1,33,[np_ball.shape[0],])
            self.model.fit(rdnum, np_ball[:,i], epochs = epoch, verbose = 0)
            rdnum = np.random.randint(1,33,[np_ball.shape[0]+1,])
            self.predict_ball.append(self.model.predict(rdnum)[-1])
        self.predict_ball = list(map(int,np.array(self.predict_ball).reshape([7,])))#[3, 7, 12, 18, 23, 27, 10]
        self.settings.set('Last_Predict',self.predict_ball)
        self.settings.set('Last_Date',datetime.datetime.now().strftime('%Y-%m-%d(%a)'))
        print(self.predict_ball)

    def send_email(self,src,passwd,dlist):
        for dest in dlist:
            try:
                content = datetime.datetime.now().strftime('%Y-%m-%d(%a)') +"\t"+ ",".join([str(x) for x in self.predict_ball]) + \
                    "\r\n"
                content += "上次预测：\r\n"+self.settings.get('Last_Date')+"\t"+self.settings.get('Last_Predict')+"\r\n\r\n\r\n\r\n"
                content += "最近几期：\r\n"
                for i in 5:
                    content += self.ball_item["id"][i][0] + "\t" + self.ball_item["date"][i][0] + "\t" +\
                        ",".join(self.ball_item['number'][i]) + "\r\n"
                msg=MIMEText(content,'plain','utf-8')
                msg["From"]=formataddr(["双色球",src])
                msg["To"]=formataddr([dest,dest])
                msg['Subject']="double chromosphere predict"        
                server=smtplib.SMTP_SSL("smtp.163.com")
                server.ehlo("smtp.163.com")
                server.login(src,passwd)
                server.sendmail(src,[dest,],msg.as_string())
                server.quit()
            except Exception as e:
                pass

    def process_item(self, item, spider):
        self.ball_item = item
        self.train_model()
        self.train_data(100)
        self.send_email("sofu456@163.com","SXDCVVWMKJBUWLMY",["463200698@qq.com"])#,"755182844@qq.com"